package com.liziba.trend.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.liziba.trend.api.IndexData;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @auther LiZiBa
 * @date 2021/2/2 21:15
 * @description: 指数数据服务
 **/

@Configuration
@CacheConfig(cacheNames = "index_data")
public class IndexDataService {

    /**
     * 日志类
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(IndexDataService.class);

    /**
     * 保存第三方服务获取的数据
     */
    private List<IndexData> indexData;

    /**
     * http请求
     */
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取第三方服务数据，并更新redis缓存
     * 第三方服务调用失败，则启动断路策略
     * @param code
     * @return
     */
    @HystrixCommand(fallbackMethod = "thirdPartNotConnected")
    @CachePut(key = "'indexData-code-' + #p0")
    public List<IndexData> fresh(String code) throws Exception {
        try {
            indexData = fetchIndexDataFromThirdPart(code);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return indexData;
    }

    @Cacheable(key = "'indexData-code-' + #p0")
    public List<IndexData> get(String code) {
        return CollUtil.toList();
    }

    @CachePut(key = "'indexData-code-' + #p0")
    public List<IndexData> store(String code) {
        return indexData;
    }

    @CacheEvict(key = "'indexData-code-' + #p0")
    public void remove(String code) {

    }

    /**
     * 从third-part-index-data-project 获取基金数据数据
     * @return
     */
    public List<IndexData> fetchIndexDataFromThirdPart(String code) {
//        List<Map> tempIndexData = restTemplate.getForObject(String.format("http://127.0.0.1:8090/indexes/%s.json", code), List.class);
        String fundEquityData = restTemplate.getForObject(String.format("http://127.0.0.1:8090/fundEquity/%s", code), String.class);
        return map2Index(fundEquityData);
    }


    /**
     * String装IndexData
     * @param fundEquityData
     * @return
     */
    private List<IndexData> map2Index(String fundEquityData) {
        LinkedList<IndexData> indexDataList = JSON.parseObject(fundEquityData, new TypeReference<LinkedList<IndexData>>() {
        });
        return indexDataList;
    }


    /**
     * Map转IndexData
     * @param tempCodes
     * @return
     */
    private List<IndexData> map2Index(List<Map> tempCodes) {
        List<IndexData> indexDataList = new ArrayList<>();
        for (Map tempCode : tempCodes) {
            String date = tempCode.get("date").toString();
            float closePoint = Convert.toFloat(tempCode.get("closePoint"));
            IndexData indexData = new IndexData(date, closePoint);
            indexDataList.add(indexData);
        }
        return indexDataList;
    }

    /**
     * 从第三方数据服务接口获取数据失败，触发断路器方法
     * @return
     */
    private List<IndexData> thirdPartNotConnected(String code) {
        LOGGER.error("断路器触发：thirdPartNotConnected()");
        IndexData indexData = new IndexData();
        indexData.setDate("n/a");
        indexData.setClosePoint(0);
        return CollectionUtils.arrayToList(indexData);
    }


}
